<template>
  <div v-loading.fullscreen.lock="loading">
    <!-- 引导 -->
    <div id="portalGuide"></div>

    <div
      class="portal-container"
      v-if="doorType && JSON.stringify(doorType) !== '{}'"
    >
      <!-- 门户模板列表 -->
      <PortalTemplateList
        :door-list="filterDoorList"
        :door-type="doorType"
        @changeDoor="changeDoor"
        id="portalTemplateList"
        ref="portalTemplateList"
      />

      <template v-if="show">
        <!-- 主页展示区域 -->
        <PortalView
          :is-open-register="isOpenRegister"
          :tenant-id="tenantId"
          :door-type="doorType"
        />

        <!-- 主页配置区域 -->
        <PortalSetting
          ref="portalSettingRef"
          :tenant-id="tenantId"
          :door-type="doorType"
          :portal-auth="portalAuth"
          @editDoorType="editDoorType"
        />
      </template>
    </div>
  </div>
</template>

<script>
import {
  reactive,
  ref,
  toRefs,
  onMounted,
  onBeforeMount,
  watch,
  nextTick,
  provide,
  computed,
} from 'vue';

import PortalTemplateList from './components/PortalTemplateList';
import PortalView from './components/PortalView';
import PortalSetting from './components/PortalSetting';
/* api */
import {
  getDoorTypeList,
  getDoorAuth,
  createDoorType,
  deleteDoorType,
  copyDoorType,
  updateDoorType,
} from '@src/api/PortalApi.ts';
/* use */
import { useTenantId } from '@hooks/useRootWindow.ts';
/* util */
import { getConfig } from '@src/api/ProductV2Api';
import { Message } from 'element-ui';
import domGuide from '@src/common/Guide'
import { getRootWindow } from '@src/util/dom';
// import { storageGet, storageSet } from '@src/util/storage';
import { PORTAL_HOMEPAGE_GUIDE } from '@src/component/guide/productV2Store';
import { getUserGuideStorageBase, setUserGuideStorageBase } from 'src/util/guideStorage.ts';
import { languages } from "@src/util/languages.js";
export default {
  components: {
    PortalTemplateList,
    PortalView,
    PortalSetting,
  },
  setup(props, { next }) {

    const portalTemplateList = ref(null);
    const portalSettingRef = ref(null);
    // 多语灰度
    const isMultiLanguage = computed(() => {
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.multiLanguage ?? false;
    });
    // 门户小程序灰度
    const isDoorApplet = computed(() => {
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.doorAppletGeneric ?? false;
    }); 
    
    const state = reactive({
      showPage: false,
      show: true,
      doorType: {}, // 当前模板数据
      doorList: [],
      portalAuth: {
        doorRenovation: false,
        currencySetting: false,
        lookShare: false,
        memberManage: false,
        doorSwitch: false,
        updateShare: false,
      },
      isOpenRegister: false,
      loading:true,
      model: {}
    });

    // 语言列表
    const languagesList = computed(() => {
      // return languages
      // const RootWindow = getRootWindow(window);
      // let list = RootWindow?.languages ?? [{
      //   'language':'zh',
      //   'code': 'zh',
      //   'description': '简体中文',
      //   'remark': '简体中文'
      // }];
      console.log(languages, 999343)
      return languages.map((v)=>{
        state.model[v.languages] = ''
        return {
          code:v.languageKey,
          ...v
        }
      })
    });

    const tenantId = useTenantId();

    const filterDoorList = computed(() => {
      state.doorList.map(v => {
        // isMultilingual：是否多语言
        v.isMultilingual = (v?.setting?.language ?? []).length > 1;
        // zh_CN_NAME：不管是不是多语言都显示中文门户名字
        v.zh_CN_NAME = (v?.setting?.doorNameLanguage ?? {})['zh'];
        return v;
      });
      return state.doorList;
    });

    const fetchDoorTypeList = () => {
      return getDoorTypeList({ tenantId: tenantId.value })
        .then(result => {
          if (!result.success) {
            Message.error(result.message);
            return Promise.reject(result.message);
          }
          state.doorList = result.data;
        })
        .catch(error => {
          console.warn(error);
          Message.error('网络错误');
        });
    };

    const editDoorType = async config => {
      const { editType } = config;

      // 创建模板
      if (editType == 'create') {
        try {
          const { params } = config;
          const { code, msg } = await createDoorType(params);
          if (code == 200) {
            Message.success('创建成功');
            await fetchDoorTypeList();
            state.doorType = filterDoorList.value[state.doorList.length - 1];
            nextTick(() => {
              portalTemplateList.value.scrollBottom();
            });
          } else {
            Message.error(msg);
          }
        } catch (error) {
          console.log(error);
          Message.error('网络错误');
        }
      }

      // 删除模板
      if (editType == 'delete') {
        try {
          const { params } = config;
          const { code, msg } = await deleteDoorType(params);
          if (code == 200) {
            Message.success('删除成功');
            await fetchDoorTypeList();
            // 如果删除的是选中的模板，默认第一个为选中模板
            if (state.doorType.id == params.id) {
              state.doorType = filterDoorList.value[0];
            }
            nextTick(() => {
              portalTemplateList.value.scrollTop();
            });
          } else {
            Message.error(msg);
          }
        } catch (error) {
          console.log(error);
          Message.error('网络错误');
        }
      }

      // 更新模板
      if (editType == 'update') {
        try {
          const { params } = config;
          const { code, msg } = await updateDoorType(params);
          if (code == 200) {
            const index = state.doorList.findIndex(v => v.id === params.id);
            await fetchDoorTypeList();
            state.doorType = filterDoorList.value[index];
          } else {
            Message.error(msg);
          }
        } catch (error) {
          console.log(error);
          Message.error('网络错误');
        }
      }

      // 复制模板
      if (editType == 'copy') {
        try {
          const { params } = config;
          const { code, msg } = await copyDoorType(params);
          if (code == 200) {
            Message.success('复制成功');
            await fetchDoorTypeList();
            state.doorType = filterDoorList.value[state.doorList.length - 1];
            nextTick(() => {
              portalTemplateList.value.scrollBottom();
            });
          } else {
            Message.error(msg);
          }
        } catch (error) {
          console.log(error);
          Message.error('网络错误');
        }
      }
    };

    const getPortalAuth = async () => {
      try {
        const { status, data } = await getDoorAuth();
        if (status !== 0) return;
        state.portalAuth = data;
      } catch (error) {
        console.error('getPortalAuth error', error);
        Message.error('网路错误');
      }
    };

    const isOpenRegisterCheck = () => {
      getConfig({
        configCode: ['PRODUCT_REGISTRATION'],
      })
        .then(res => {
          if (res.errorCode === 0) {
            state.isOpenRegister = !!res?.data[0]?.isOpen;
          }
        })
        .catch(err => {
          console.error('isOpenRegisterCheck error', error);
          Message.error('网路错误');
        });
    };

    const refresh = () => {
      state.show = false;
      nextTick(() => {
        state.show = true;
      });
    };

    const changeDoor = i => {
      state.doorType = filterDoorList.value[i];
    };

    const guide = (userGuideStroage) => {
      domGuide([
        {
          content: '门户可创建多个模版，支持独立启用/停用。',
          haveStep: true,
          nowStep: 1,
          totalStep: 2,
          id: 'portalGuide',
          // domId: 'portalView',
          domId: 'portalTemplateList',
          needCover: true,
          direction:'row'
          // lastFinish: true,
        },
        {
          content: '点击进入门户搭建页面。',
          haveStep: true,
          nowStep: 2,
          totalStep: 2,
          id: 'portalGuide',
          domObj: () => { return portalSettingRef.value.multiLanguageRef },
          needCover: true,
          finishBtn: '完成',
          // lastFinish: true,
        },
      ], 0, '', (e) => {
        return new Promise((resolve, reject) => {
          resolve();
        })
      })
        .create()
        .then(res_ => {
          // if (res_) storageSet(PORTAL_HOMEPAGE_GUIDE, '1');
          if (res_) {
            setUserGuideStorageBase({
              userGuideList: [
                {
                  type: PORTAL_HOMEPAGE_GUIDE,
                  step: 1,
                  isComplete: 1
                }
              ]
            }, userGuideStroage).then(res=>{
              userGuideStroage = res;
            });
          }
        });
    };

    const initGuide = async () => {
      let userGuideStroage = await getUserGuideStorageBase();
      if (!Object.keys(userGuideStroage).includes(PORTAL_HOMEPAGE_GUIDE)) {
        setTimeout(() => {
          guide(userGuideStroage);
        }, 1000);
      } 
      // else {
      //   domGuide.destroy('portalGuide');
      // }

      // nextTick(() => {
      //   if (
      //     storageGet(PORTAL_HOMEPAGE_GUIDE)
      //     && storageGet(PORTAL_HOMEPAGE_GUIDE) > 0
      //   ) {
      //     domGuide.destroy('portalGuide');
      //   } else {
      //     setTimeout(() => {
      //       guide();
      //     }, 1000);
      //   }
      //   // setTimeout(() => {
      //   //   guide();
      //   // }, 1000);
      // });
    }

    watch(
      () => state.doorType,
      (newVal, oldVal) => {
        if (newVal.id != oldVal.id) refresh();
      },
      {
        deep: true,
      }
    );

    onMounted(() => {
      getPortalAuth();
      isOpenRegisterCheck();

      nextTick(() => {
        initGuide();
      });
    });

    onBeforeMount(() => {
      fetchDoorTypeList().then(() => {
        let _doorId = sessionStorage.getItem('_doorId')
        let index = 0

        if(_doorId){
          index = state.doorList.findIndex(v => v.id == _doorId);
          sessionStorage.removeItem('_doorId')
          nextTick(()=>{
            setTimeout(()=>{
              document.querySelectorAll('.template-item')[index].scrollIntoView()
            }, 500)
          })
        } 

        state.doorType = filterDoorList.value[index]

      }).finally(()=>{
        state.loading = false
      });
    });
    provide('editDoorType', editDoorType);
    provide('isMultiLanguage', isMultiLanguage)
    provide('languagesList', languagesList)
    provide('model', state.model)
    provide('isDoorApplet', isDoorApplet)
    return {
      ...toRefs(state),
      filterDoorList,
      tenantId,
      portalTemplateList,
      portalSettingRef,
      editDoorType,
      changeDoor,
      isMultiLanguage
    };
  },
};
</script>

<style lang="scss" scoped>
.portal-container {
  display: flex;
  justify-content: space-between;
}
</style>
